package com.xx.eshop.controller;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xx.eshop.entity.Category;
import com.xx.eshop.service.CategoryService;

@Controller
public class CategoryController {
	
	@Autowired
	private CategoryService categoryService;
	

	
	
	@RequestMapping("/admin/category/index")
	public String index() {
		return "/admin/category/index";
	}
	
	@RequestMapping("/admin/category/findAll")
	@ResponseBody
	public Map<String, Object> findAll() {
		Map<String, Object> map = new HashMap<>();
		map.put("rows", categoryService.findAll());
		return map;
	}
	
	@RequestMapping("/admin/category/findNextId")
	@ResponseBody
	public Map<String, Object> findNextId(int pid) {
		Map<String, Object> map = new HashMap<>();
		map.put("next", categoryService.findNextId(pid));
		return map;
	}
	
	@RequestMapping("/admin/category/findByPid")
	@ResponseBody
	public Map<String, Object> findByPid(Integer pid) {
		Map<String, Object> map = new HashMap<>();
		if(pid != null) {
			map.put("rows", categoryService.findByPid(pid));
		} else {
			map.put("rows", Collections.emptyList());
		}
		return map;
	}
	
	@RequestMapping("/admin/category/save")
	@ResponseBody
	public Map<String, Object> save(Category category) {
		Map<String, Object> map = new HashMap<>();
		categoryService.save(category);
		map.put("success", true);
		return map;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/admin/category/update")
	@ResponseBody
	public Map<String, Object> update(Category category, String rows) throws JsonParseException, JsonMappingException, IOException {
//		System.out.println(category);
//		System.out.println(rows);
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Integer> rowsmap = mapper.readValue(rows, Map.class);
		System.out.println(rowsmap);
		
		categoryService.update(category, rowsmap);
		
		Map<String, Object> map = new HashMap<>();		
		map.put("success", true);
		return map;
	}

}
